import json
import logging
from urllib.parse import urlencode

logger = logging.getLogger()

class LoggingMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # 记录请求信息
        data_json = ''
        if request.body:
            data = json.loads(request.body.decode())
            data_json = json.dumps(data, separators=(', ', ': '), ensure_ascii=False)

        separator = ''
        if request.GET:
            separator = '?'

        logger.info(f'Request: {request.method} {request.path}{separator}{urlencode(request.GET)} {data_json}')

        response = self.get_response(request)

        # 记录响应信息
        logger.info(f'Response: {response.status_code}, data:{json.dumps(response.data, ensure_ascii=False)}')

        return response